<template>
  <div class="show_report" id="show_report" ref="show_report">
    <div class="report_title">{{title}}</div>
    <a-card :bordered="false" class="search_show_report" v-if="form_view.length">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" :labelCol="{span:8}" :wrapperCol="{span: 16, offset: 0}">
          <a-row :gutter="{xs: 10, sm: 15, md: 20, lg: 25, xl: 30}" align="bottom">
            <a-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-for="(item, index) in form_view" :key="index">
              <a-form-item :label="item.name">
                <template v-if="item.type == 'input'">
                  <a-input placeholder="请输入" v-model="form[item.name]"  />
                </template>
                <template v-if="item.type == 'select'">
                  <a-select
                    :maxTagTextLength="100"
                    show-search v-model="form[item.name]"
                    placeholder="请选择"
                    :loading="loading1"
                    @dropdownVisibleChange="onDropdownSelect(item, $event)"
                    @search="onSearchSelectValue1(item, $event)"
                    allow-clear
                  >
                    <a-select-option v-for="(sele1, index) in selectsArr1" :value="sele1.value" :key ="sele1.value +'-'+ index">
                      {{sele1.displayName}}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="item.type == 'selects'">
                  <a-select
                    mode="multiple"
                    show-search
                    placeholder="请选择"
                    v-model="form[item.name]"
                    :loading="loading2"
                    @dropdownVisibleChange="onDropdownSelects(item, $event)"
                    @search="onSearchSelectValue2(item, $event)"
                    allow-clear
                  >
                    <a-select-option v-for="(sele2, idx) in selectsArr2" :value="sele2.value" :key ='sele2.value + "-" +idx'>
                      {{sele2.displayName}}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="item.type == 'date-range'">
                  <a-range-picker v-model="form[item.name]" @change="onRangePicker(item.name, $event)" />
                </template>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" style="float: right;">
                <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="onSearch" :loading="search_loading">查询</a-button>
                  <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'"/>
                  </a>
                </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <grid-layout
      :layout.sync="layout"
      :col-num="24"
      :row-height="itemGridHeight"
      :is-draggable="false"
      :is-resizable="false"
      :is-mirrored="false"
      :vertical-compact="false"
      :margin="[10, 10]"
      :auto-size="false"
      :static="true"
      :use-css-transforms="true"
      ref="grid_layout"
    >
      <grid-item
        v-for="item in layout"
        :x="item.x"
        :y="item.y"
        :w="item.w"
        :h="item.h"
        :i="item.i"
        :key="item.i"
        style="touch-action: none;"
      >
        <a-card style="width: 100%; height: 100%;padding: 8px 4px 2px 4px;">
          <div class="card-title">
            <div class="card-title_title">
              <div class="chart_title">
                {{getChartInfo(item.i).title}}
              </div>
              <div class="chart_action" v-if="getChartInfo(item.i).type == 'table'">
                <a-button type="link" size="small" @click="onExportExcel(getChartInfo(item.i))">导出excel</a-button>
              </div>
            </div>
            <div class="card-title_remark" v-show="getChartInfo(item.i).remark">
              {{getChartInfo(item.i).remark}}
            </div>
          </div>
          <NumberChart
            v-if="getChartInfo(item.i).type == 'number'"
            :item="getChartInfo(item.i)"
            :remark="getChartInfo(item.i).remark"
            :display="getChartInfo(item.i).display"
            :dataMapping="getChartInfo(item.i).dataMapping"
            :datasetList="datasetList"
            :itemGridHeight="itemGridHeight"
            :search_loading="echarts_loading"
            :position="getChartInfo(item.i).position"
            :ref="'chart_ref'+item.i"
          >
          </NumberChart>
          <PathView
            v-else-if="getChartInfo(item.i).type == 'path'"
            :item="getChartInfo(item.i)"
            :remark="getChartInfo(item.i).remark"
            :display="getChartInfo(item.i).display"
            :dataMapping="getChartInfo(item.i).dataMapping"
            :datasetList="datasetList"
            :itemGridHeight="itemGridHeight"
            :search_loading="echarts_loading"
            :position="getChartInfo(item.i).position"
            :ref="'chart_ref'+item.i"
          >
          </PathView>
          <Retention
            v-else-if="getChartInfo(item.i).type == 'retention'"
            :item="getChartInfo(item.i)"
            :remark="getChartInfo(item.i).remark"
            :display="getChartInfo(item.i).display"
            :dataMapping="getChartInfo(item.i).dataMapping"
            :datasetList="datasetList"
            :itemGridHeight="itemGridHeight"
            :search_loading="echarts_loading"
            :position="getChartInfo(item.i).position"
            :ref="'chart_ref'+item.i"
          >
          </Retention>
          <TableChart
            v-else-if="getChartInfo(item.i).type == 'table'"
            :item="getChartInfo(item.i)"
            :remark="getChartInfo(item.i).remark"
            :display="getChartInfo(item.i).display"
            :dataMapping="getChartInfo(item.i).dataMapping"
            :datasetList="datasetList"
            :itemGridHeight="itemGridHeight"
            :search_loading="echarts_loading"
            :position="getChartInfo(item.i).position"
            :ref="'chart_ref'+item.i"
          >
          </TableChart>
          <EchartItem
            v-else
            :item="getChartInfo(item.i)"
            :remark="getChartInfo(item.i).remark"
            :display="getChartInfo(item.i).display"
            :dataMapping="getChartInfo(item.i).dataMapping"
            :datasetList="datasetList"
            :itemGridHeight="itemGridHeight"
            :search_loading="echarts_loading"
            :position="getChartInfo(item.i).position"
            :ref="'chart_ref'+item.i"
          >
          </EchartItem>
        </a-card>
      </grid-item>
    </grid-layout>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import VueGridLayout from 'vue-grid-layout';
import { export2Excel } from '@/excel/excel.config';
import elementResize from '@/views/reportForms/show_report/elementResize';
import { baseMixin } from '@/store/app-mixin';
import EchartItem from './show_report/echarts_item.vue';
import NumberChart from './show_report/number_chart.vue';
import PathView from './show_report/pathView.vue';
import Retention from './show_report/retention.vue';
import TableChart from './show_report/table_chart.vue';
import {debounce} from "@/components/OptimizeUtils";
import {isEmptyString} from "@/utils/util";

export default {
  name: "publicReports",
  mixins: [baseMixin],
  data () {
    return {
      reportDetail: null,
      advanced: false,
      rowLength: 6,
      title: '报表展示',
      form: {},
      selectsArr1: [],
      selectsArr2: [],
      datasetList: {},
      chart_view: [],
      control_type: [],
      filter_open: [],
      loading1: false,
      loading2: false,
      itemGridHeight: 30,
      init_filters: [],
      init_datasetIds: [],
      search_loading: false,
      echarts_loading: false,
      filterSelectId: '',
      filterSelectValue: ''
    }
  },
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    EchartItem,
    NumberChart,
    PathView,
    Retention,
    TableChart
  },
  watch: {
    look_id () {
      this.selectsArr1 = [];
      this.selectsArr2 = [];
      this.filter_open = [];
      this.control_type = [];
      this.search_loading = true;
      this.init_report()
      this.$nextTick(()=> {
        this.setRowHeight()
      })
    }
  },
  computed: {
    ...mapState('reportManage', ['datail', 'dataset']),
    ...mapState('custom', ['report']),
    form_view () {
      if (this.advanced) {
        return this.filter_open
      } else {
        return this.control_type
      }
    },
    look_id () {
      return this.$route.params.id;
    },
    sharingKey (){
      return this.$route.query.key;
    },
    layout () {
      return this.chart_view.map(chart =>{
        return {...chart.position, 'i': `${chart.id}`};
      })
    }
  },
  methods: {
    ...mapActions('publicReportManage',['getReportList', 'getReportDetail', 'getDatasetData', 'getFilterValue']),
    /**
     * 表格导出excel表
     */
    onExportExcel (value) {
      this.$confirm({
        title: '提示',
        content: `你确定要导出 ${value.title} 该表格里的数据吗`,
        onOk:()=> {
          let ref = this.$refs;
          let getVal = [];
          for (let key in ref) {
            if (key.includes('chart_ref')) {
              getVal.push(key);
            }
          }
          let data = null,
            columns = null;
          getVal.forEach(item => {
            if (this.$refs[item][0] && this.$refs[item][0].item.id == value.id) {
              columns = this.$refs[item][0].columns;
              data = this.$refs[item][0].datasetArr;
            }
          })
          export2Excel(columns, data, value.title);
        },
        onCancel() {},
      });
    },
    getChartInfo (id) {
      let chartVal = null;
      this.chart_view.forEach(chart=>{
        if (chart.id == id) {
          chartVal = chart;
        }
      })
      return chartVal;
    },
    onRangePicker (value, date) {
      if (date.length) {
        this.form[value] = [this.moment(date[0]).format('YYYY-MM-DD'), this.moment(date[1]).format('YYYY-MM-DD') ]
      }
    },
    // 展开收起
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onSearchSelectValue1 (item, value) {
      this.filterSelectId = item.id;
      this.filterSelectValue = value;
      if (value) {
        this.loading1 = true;
        let query = debounce(this.getFilterValue1,1000);
        query(value);
      }
    },
    getFilterValue1 () {
      if (isEmptyString(this.sharingKey)){
        return
      }
      const query = {keyword: this.filterSelectValue, key: this.sharingKey}
      this.getFilterValue({ id: this.filterSelectId, reportId: this.look_id, query: query })
        .then(res => {
          this.loading1 = false;
          this.selectsArr1 = [...res.data];
        })
        .catch(error => {
          this.loading1 = false;
        })
    },
    getFilterValue2 () {
      if (isEmptyString(this.sharingKey)){
        return
      }
      const query = {keyword: this.filterSelectValue, key: this.sharingKey}
      this.getFilterValue({ id: this.filterSelectId, reportId: this.look_id, query: query })
        .then(res => {
          this.loading2 = false;
          this.selectsArr2 = [...res.data];
        })
        .catch(error => {
          this.loading2 = false;
        })
    },
    onSearchSelectValue2 (item, value) {
      this.filterSelectId = item.id;
      this.filterSelectValue = value;
      if (value) {
        this.loading2 = true;
        let query = debounce(this.getFilterValue2,1000);
        query(value)
      }
    },
    onDropdownSelect (item, e) {
      if (e) {
        if (isEmptyString(this.sharingKey)){
          return
        }
        this.getFilterValue({ id: item.id, reportId: this.look_id, query:{key: this.sharingKey} })
          .then(res=> {
            this.selectsArr1 = [...res.data];
          })
          .catch(error => {
            this.loading1 = false;
          })
      }
    },
    onDropdownSelects (item, e) {
      if (e) {
        this.getFilterValue({ id: item.id, reportId: this.look_id, query:{key: this.sharingKey} })
          .then(res=> {
            this.selectsArr2 = [...res.data];
          })
          .catch(error => {
            this.loading2 = false;
          })
      }
    },
    onReset (){
      this.form = {}
      this._set_filter(this.reportDetail)
    },
    onSearch () {
      this.search_loading = true;
      this.echarts_loading = true;
      let queryForm = this.queryFilterForm(this.form, this.init_filters, this.init_datasetIds);
      let deleteArr = [],
        retainArr = [];
      for (let key in queryForm) {
        if (queryForm[key].length == 0) {
          deleteArr.push(key);
        } else {
          retainArr.push(key)
        }
      }
      retainArr.forEach(data => {
        delete this.datasetList[data]
      })
      let wait = []
      retainArr.forEach(data => {
        wait.push(this.PromiseData({id: data, filter: JSON.stringify(queryForm[data])}))
      })
      let promiseArr = wait.filter(item => {
        if(item) {return item}
      })
      Promise.all(promiseArr.map(item=>item.catch(()=>{status: 'failed'}))).then(res =>{
        this.$nextTick(() => {
          this.layout.forEach(chart => {
            let type = this.$refs['chart_ref' + chart.i][0].item.type;
            let vNode = this.$refs['chart_ref' + chart.i][0];
            if (type == 'table') {
              vNode.dataConfig();
              vNode.initTableConfig();
            } else if (type == 'number') {
              vNode.initNumber();
            } else if (type == 'path') {
              vNode.reset_sankeyHeight();
            } else if (type == 'retention') {
              vNode.tableInit();
            } else {
              vNode.initCharts();
            }
          })
        })
        this.search_loading = false;
        this.echarts_loading = false;
      }).catch(error => {
        this.search_loading = false;
        this.echarts_loading = false;
      })
    },
    _set_filter (detail) {
      this.init_filters = detail.data.filters.map( filter => {
        // 根据筛选信息的控件类型对数据做处理
        if (filter.type == 'date-range') {
          let filterDefaultValue = JSON.parse(filter.defaultValue);
          if (filterDefaultValue.type == 'absolute') {
            let date_Array = (filterDefaultValue.values);
            this.$set(this.form, filter.name, [this.moment(date_Array[0]).format('YYYY-MM-DD'), this.moment(date_Array[1]).format('YYYY-MM-DD') ])
          } else {
            let date_Array = (filterDefaultValue.values).split(',');
            this.$set(this.form, filter.name, [this.moment().subtract(parseInt(date_Array[0]), 'days').format('YYYY-MM-DD'), this.moment().subtract(parseInt(date_Array[1]), 'days').format('YYYY-MM-DD') ])
          }
        } else {
          // 当控件类型为多选下拉菜单，需要将默认值转为数组
          if (filter.type == 'selects') {
            let filterDefaultValue = filter.defaultValue;
            this.$set(this.form, filter.name, filterDefaultValue ? filterDefaultValue.split(',') : [])
          } else {
            this.$set(this.form, filter.name, filter.defaultValue)
          }
        }
        let filterVal = null;
        if (filter.type == 'date-range') {
          filterVal = {...filter, config: JSON.parse(filter.config), defaultValue: JSON.parse(filter.defaultValue)}
        } else {
          filterVal = {...filter, config: JSON.parse(filter.config), defaultValue: filter.defaultValue}
        }
        return filterVal;
      })
    },
    init_report () {
      // 获取当前查看报表的基本信息
      this.echarts_loading = true;
      this.look_id && this.sharingKey && this.getReportList({id: this.look_id, key:this.sharingKey})
        .then(report =>{
          this.title = report.data.name
        })
        .catch(err => {
          if (err.code == 401) {
            this.err401(err)
            return
          }
          this.$message.error('获取报表失败，原因：' + err.msg + '！')
        })
      // 获取当前查看报表的详情（图表配置、筛选字段配置）
      this.look_id && this.sharingKey && this.getReportDetail({id: this.look_id, key: this.sharingKey})
        .then(detail => {
          this.reportDetail = JSON.parse(JSON.stringify(detail))
          // 当前报表使用的数据集
          this.init_datasetIds =  detail.data.datasetIds
          // 当前报表配置的图表信息
          this.chart_view = detail.data.charts.map( item => {
            return {...item, dataMapping: JSON.parse(item.dataMapping), display: JSON.parse(item.display), position: JSON.parse(item.position)}
          })
          // 当前报表的筛选信息
          this._set_filter(detail)
          // 设置控件排列
          this.init_filters.forEach((filter, index) => {
            if (index < 2) {
              this.control_type.push({type: filter.type, name: filter.name, id: filter.id})
            }
            this.filter_open.push({type: filter.type, name: filter.name, id: filter.id})
          })

          let queryForm = this.queryFilterForm(this.form, this.init_filters, this.init_datasetIds)
          this.datasetList = {}
          let wait = [];
          this.init_datasetIds.forEach(data => {
            wait.push(this.PromiseData({id: data, filter: JSON.stringify(queryForm[data])}))
          })

          let promiseAll = wait.filter(item => {
            if (item) return item
          })

          Promise.all(promiseAll.map(item=>item.catch(()=>{status: 'failed'})))
            .then(res => {
              this.$nextTick(() => {
                this.layout.forEach(chart => {
                  let type = this.$refs['chart_ref' + chart.i][0].item.type;
                  let vNode = this.$refs['chart_ref' + chart.i][0];
                  if (type == 'table') {
                    vNode.dataConfig();
                    vNode.initTableConfig();
                  } else if (type == 'number') {
                    vNode.initNumber();
                  } else if (type == 'path') {
                    vNode.reset_sankeyHeight();
                  } else if (type == 'retention') {
                    vNode.tableInit();
                  } else {
                    vNode.initCharts();
                  }
                })
                this.echarts_loading = false;
                this.search_loading = false;
              })
            })
            .catch(err => {
              this.echarts_loading = false;
              this.search_loading = false;
            })

          let reportHeight = this.layout.sort((a, b)=> {
            return a.y-b.y
          })
          if (reportHeight.length == 0) {
            return
          }
          this.$refs.show_report.style.height = `${(reportHeight[reportHeight.length-1].y + reportHeight[reportHeight.length-1].h) * (this.itemGridHeight+20)}px`;
        }).catch(err => {
          console.error(err)
          if (err && err.code === 403){
            this.$message.warning("报表分享已过期，请在自定义报表中重新分享")
          }else {
            this.$message.warning("报表异常，内部错误：" + err)
          }
        })
    },
    // 配置查询参数
    queryFilterForm (Query, filters, datasetIds) {
      // 以{key:value}的形式生成每个数据集的查询参数
      let filterValue = {}
      for (let j = 0; j < datasetIds.length; j++) {
        // 生成每个数据集对应的数组存放条件
        filterValue[datasetIds[j]] = []
        for (let i = 0; i < filters.length; i++) {
          // 控件类型为日期时，需要做start和end的特殊处理
          if (filters[i].type == 'date-range') {
            let config_start = filters[i].config.start,
              config_end = filters[i].config.end,
              count = 0;
            for (let m = 0; m < config_start.length; m++) {
              if (config_start[m].datasetId == datasetIds[j]) {
                for (let key in Query) {
                  if (filters[i].name == key) {
                    filterValue[datasetIds[j]].push({
                      filterName: config_start[m].filterName,
                      value: Query[key][count]
                    })
                    count = 1;
                  }
                }
              }
            }
            for (let n = 0; n < config_end.length; n++) {
              if (config_end[n].datasetId == datasetIds[j]) {
                for (let key in Query) {
                  if (filters[i].name == key) {
                    filterValue[datasetIds[j]].push({
                      filterName: config_end[n].filterName,
                      value: Query[key][count]
                    })
                    count = 1;
                  }
                }
              }
            }
          } else {
            let config_item = filters[i].config
            for (let o = 0; o <config_item.length; o++) {
              if (config_item[o].datasetId == datasetIds[j]) {
                for(let key in Query) {
                  if (filters[i].name == key) {
                    // 当控件类型为单选和多选 需要转换数据类型
                    if (filters[i].type == 'select' || filters[i].type == 'selects') {
                      if (Query[key]) {
                        filterValue[datasetIds[j]].push({
                          filterName: config_item[o].filterName,
                          value: Query[key] instanceof Array ? Query[key] : Query[key].split(',')
                        })
                      } else {
                        filterValue[datasetIds[j]].push({
                          filterName: config_item[o].filterName,
                          value: Query[key]
                        })
                      }
                    } else {
                      filterValue[datasetIds[j]].push({
                        filterName: config_item[o].filterName,
                        value: Query[key]
                      })
                    }
                  }
                }
              }
            }
          }
        }
      }
      return filterValue
    },
    PromiseData (params) {
      if (isEmptyString(this.sharingKey)){
        return
      }else {
        params.key = this.sharingKey
      }
      return new Promise((resolve, reject) => {
        this.getDatasetData(params)
          .then(res=>{
            this.$set(this.datasetList, params.id, res.data)
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
            this.$message.error('查询错误，原因：' + err.msg + '！')
            setTimeout(() => {
              this.search_loading = false;
            }, 1500)
            console.error(err)
          })
      })
    },
    setRowHeight () {
      let rowH = this.$refs.show_report && this.$refs.show_report.offsetWidth
      this.itemGridHeight = Math.floor(rowH/24)-15;
    }
  },
  created () {
    this.init_report()
  },
  mounted() {
    this.setRowHeight()
    elementResize.on(document.getElementById('show_report'), () => {
      let rowH = this.$refs.show_report && this.$refs.show_report.offsetWidth
      this.itemGridHeight = Math.floor(rowH/24)-15;
    })
  },
}
</script>

<style scoped>
.report_title {
  font-size: 24px;
  font-weight: bold;
  line-height: 60px;
  margin-top: -15px;
}

.search_show_report {
  width: 100%;
  padding: 24px 24px 0px;
  /* margin-bottom: 12px; */
}

.show_report {
  width: 100%;
  height: 100%;
}

.show_report>>>.ant-card-body{
  width: 100%;
  height: 100%;
  padding: 0px;
}

.card-title {
  height: 35px;
}

.card-title_title {
  display: flex;
  justify-content: space-between;
}

.chart_title {
  font-weight: bold;
  font-size: 16px;
  color: black;
  text-indent: 10px;
  line-height: 30px;
}

.card-title_remark {
  padding-right: 20px;
  font-size: 12px;
  line-height: 20px;
  color: #8492a6;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-indent: 10px;
  margin-bottom: 2px;
}

.chart_action {
  display: flex;
  align-items: center;
}

.show_report >>> span.table-page-search-submitButtons {
  float: right;
}

.show_report >>> .vue-grid-layout {
  width: calc(100% + 20px);
  margin-left: -10px;
}

.search_show_report .search_show_report >>>label {
  overflow: hidden;
}

.show_report {
  flex: 1;
}

</style>
